<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<!--增加加载进度条功能CSS-->
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>

    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="JAVA,泛型," />





  <link rel="alternate" href="/atom.xml" title="卡卢比-Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="一、为什么使用泛型1.可读性好，一看泛型就知道里面装的什么类型的元素2.泛型只在编译前存在，编译后会将类型擦除并替换成其限定类型，编译后就是一个普通类。泛型可以在编译前规范代码，防止放入一些不合格的对象导致运行期报错，提高程序健壮性。3.使用泛型让程序更灵活，各类框架就大量使用泛型  个人理解：泛型可以大概分为两部分：定义泛型和使用泛型，大多数时候我们是在使用泛型，也就是用具体类型限制，比如：Li">
<meta name="keywords" content="JAVA,泛型">
<meta property="og:type" content="article">
<meta property="og:title" content="Java基础之泛型总结">
<meta property="og:url" content="http://blog.lyq3.com/2017/11/07/JavaCore/java_genericity/index.html">
<meta property="og:site_name" content="卡卢比-Blog">
<meta property="og:description" content="一、为什么使用泛型1.可读性好，一看泛型就知道里面装的什么类型的元素2.泛型只在编译前存在，编译后会将类型擦除并替换成其限定类型，编译后就是一个普通类。泛型可以在编译前规范代码，防止放入一些不合格的对象导致运行期报错，提高程序健壮性。3.使用泛型让程序更灵活，各类框架就大量使用泛型  个人理解：泛型可以大概分为两部分：定义泛型和使用泛型，大多数时候我们是在使用泛型，也就是用具体类型限制，比如：Li">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://blog.lyq3.com/images/java_core/fx.jpg">
<meta property="og:updated_time" content="2018-04-30T10:44:26.097Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java基础之泛型总结">
<meta name="twitter:description" content="一、为什么使用泛型1.可读性好，一看泛型就知道里面装的什么类型的元素2.泛型只在编译前存在，编译后会将类型擦除并替换成其限定类型，编译后就是一个普通类。泛型可以在编译前规范代码，防止放入一些不合格的对象导致运行期报错，提高程序健壮性。3.使用泛型让程序更灵活，各类框架就大量使用泛型  个人理解：泛型可以大概分为两部分：定义泛型和使用泛型，大多数时候我们是在使用泛型，也就是用具体类型限制，比如：Li">
<meta name="twitter:image" content="http://blog.lyq3.com/images/java_core/fx.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.lyq3.com/2017/11/07/JavaCore/java_genericity/"/>





  <title>Java基础之泛型总结 | 卡卢比-Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卡卢比-Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">坚持看书|坚持健身|坚持码代码</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.lyq3.com/2017/11/07/JavaCore/java_genericity/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="卡卢比">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/touxiang.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卡卢比-Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java基础之泛型总结</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-07T22:19:58+08:00">
                2017-11-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/看书笔记/" itemprop="url" rel="index">
                    <span itemprop="name">看书笔记</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/看书笔记/Java核心技术卷-第10版/" itemprop="url" rel="index">
                    <span itemprop="name">Java核心技术卷(第10版)</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2017/11/07/JavaCore/java_genericity/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/11/07/JavaCore/java_genericity/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2017/11/07/JavaCore/java_genericity/" class="leancloud_visitors" data-flag-title="Java基础之泛型总结">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="一、为什么使用泛型"><a href="#一、为什么使用泛型" class="headerlink" title="一、为什么使用泛型"></a>一、为什么使用泛型</h3><p>1.可读性好，一看泛型就知道里面装的什么类型的元素<br>2.泛型只在编译前存在，编译后会将类型擦除并替换成其限定类型，编译后就是一个普通类。泛型可以在编译前规范代码，防止放入一些不合格的对象导致运行期报错，提高程序健壮性。<br>3.使用泛型让程序更灵活，各类框架就大量使用泛型</p>
<blockquote>
<p>个人理解：泛型可以大概分为两部分：定义泛型和使用泛型，大多数时候我们是在使用泛型，也就是用具体类型限制，比如：List《String》,而写一些通用工具或者框架的时候需要自己定义泛型类，泛型方法等提高程序的灵活性。</p>
</blockquote>
<p><img src="/images/java_core/fx.jpg" alt="小小牛博客"></p>
<h3 id="二、定义简单泛型类"><a href="#二、定义简单泛型类" class="headerlink" title="二、定义简单泛型类"></a>二、定义简单泛型类</h3><p>例如：</p>
<h4 id="定义泛型类："><a href="#定义泛型类：" class="headerlink" title="定义泛型类："></a>定义泛型类：</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> T second;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Pair</span><span class="params">()</span></span>&#123;first = <span class="keyword">null</span>;second = <span class="keyword">null</span>&#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">pair</span><span class="params">(T first, T second)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.first = first;</span><br><span class="line">        <span class="keyword">this</span>.second = second;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//set get 略...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<blockquote>
<p>类型变量使用大写形式，且比较短，在java库中，E表示集合的元素类型，K和V分别表示Key和值，T表示任意值，也可以使用邻近的U和S</p>
</blockquote>
<h4 id="使用泛型："><a href="#使用泛型：" class="headerlink" title="使用泛型："></a>使用泛型：</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Pair&lt;String&gt;</span><br></pre></td></tr></table></figure>
<h3 id="三、泛型方法"><a href="#三、泛型方法" class="headerlink" title="三、泛型方法"></a>三、泛型方法</h3><p>例：</p>
<h4 id="定义泛型方法"><a href="#定义泛型方法" class="headerlink" title="定义泛型方法"></a>定义泛型方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> ArrayAlg &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">getMiddle</span><span class="params">(T... a)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a[a.length / <span class="number">2</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>泛型的类型变量放在修饰符的后面（这里是public static） ，返回值的前面，泛型方法可以定义在可以定义在普通类中，也可以定义在泛型类中</p>
</blockquote>
<h4 id="使用泛型方法"><a href="#使用泛型方法" class="headerlink" title="使用泛型方法"></a>使用泛型方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">String middle = ArrayAlg.&lt;String&gt;getMiddle(<span class="string">"aaa"</span>,<span class="string">"sss"</span>,<span class="string">"sdsd"</span>);</span><br></pre></td></tr></table></figure>
<p>上面限制了是String，如果放入一个int类型的参数就会报错，大多数情况下《String》可以省略的，编译器会自己推导出限制类型；<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ArrayAlg.getMiddle(<span class="string">"aaa"</span>,<span class="number">123</span>,<span class="string">"sdsd"</span>);</span><br></pre></td></tr></table></figure></p>
<p>上面这句代码不会报错，但是编译器推导的限制类型是String 和 Integer公共父类型，如果用String接收返回值会提示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Incompatible types. Required String but <span class="string">'getMiddle'</span> was inferred to T: Incompatible types: Serializable &amp; Comparable&lt;? extends Serializable &amp; Comparable&lt;?&gt;&gt; is not convertible to String</span><br></pre></td></tr></table></figure>
<p>大概意思是可以赋值给Serializable 或 Comparable类型</p>
<h3 id="四、类型变量的限定"><a href="#四、类型变量的限定" class="headerlink" title="四、类型变量的限定"></a>四、类型变量的限定</h3><ul>
<li>我们在定义泛型的时候可以限定其范围：<br>如：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Comparable&gt; <span class="function">T <span class="title">min</span><span class="params">(T[] a)</span>...</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>我们在使用时就只能使用实现了Comparable接口的类型来限制。</p>
<blockquote>
<p>这里是接口但依然使用extends关键字，主要是为了表明是父子关系。不管是类还是接口泛型里都是使用extends</p>
</blockquote>
<ul>
<li>一个类型变量或通配符可以有多个限定<br>如：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T extends Comparable &amp; Serializable</span><br></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>可以根据需要拥有多个接口超类型，但是限定中至多有一个类，而且这个类必须在列表的第一个</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T extends <span class="class"><span class="keyword">class</span> &amp; <span class="title">interface</span> &amp; <span class="title">interface</span> &amp; <span class="title">interface</span> //就像这样的格式，如果有类，放在第一个</span></span><br></pre></td></tr></table></figure>
<h3 id="五、类型擦除"><a href="#五、类型擦除" class="headerlink" title="五、类型擦除"></a>五、类型擦除</h3><p>无论何时定义一个泛型类型，都自动提供一个原始类型，原始类型用第一个限定的类型变量来替换</p>
<p>T 是一个无限定的变量，所以会直接用Object替换，如 private T first 编译后变成 private Object first</p>
<p>如果是<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;T extends Comparable &amp; Serializable&gt;</span><br></pre></td></tr></table></figure></p>
<p>则原始类型会用第一个（即Comparable）代替，private Comparable first;</p>
<blockquote>
<p>在使用泛型的时候编译器会自动加入强制类型转换，转换成我们给定的类型</p>
</blockquote>
<p>如：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Pair&lt;String&gt; b = ...</span><br><span class="line">String ru = b.getName();</span><br></pre></td></tr></table></figure></p>
<p>类型擦除后getName返回类型会用Object替换T，编译器会插入String强制类型转换</p>
<blockquote>
<p>注意：要考虑类型擦除后带来的隐藏隐患</p>
</blockquote>
<h3 id="六、约束与局限性"><a href="#六、约束与局限性" class="headerlink" title="六、约束与局限性"></a>六、约束与局限性</h3><h4 id="1、不能用基本类型实例化类型参数"><a href="#1、不能用基本类型实例化类型参数" class="headerlink" title="1、不能用基本类型实例化类型参数"></a>1、不能用基本类型实例化类型参数</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">如：Pair&lt;<span class="keyword">int</span>&gt;不行，只能用Pair&lt;Integer&gt;</span><br></pre></td></tr></table></figure>
<h4 id="2、运行时类型查询只适用于原始类型"><a href="#2、运行时类型查询只适用于原始类型" class="headerlink" title="2、运行时类型查询只适用于原始类型"></a>2、运行时类型查询只适用于原始类型</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">例如：<span class="keyword">if</span>(a <span class="keyword">instanceof</span> Pair&lt;String&gt;) <span class="comment">//报错</span></span><br><span class="line">     ( Pair&lt;String&gt;) a <span class="comment">//强转，报错</span></span><br></pre></td></tr></table></figure>
<h4 id="3、不能创建参数化类型的数组"><a href="#3、不能创建参数化类型的数组" class="headerlink" title="3、不能创建参数化类型的数组"></a>3、不能创建参数化类型的数组</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Pair&lt;String&gt;[] table = <span class="keyword">new</span> Pair&lt;String&gt;[<span class="number">10</span>];<span class="comment">//报错，声明不会报错，但初始化就会报错</span></span><br></pre></td></tr></table></figure>
<h4 id="4、不能实例化类型变量"><a href="#4、不能实例化类型变量" class="headerlink" title="4、不能实例化类型变量"></a>4、不能实例化类型变量</h4><p>如：new T[]</p>
<h4 id="5、不能构造泛型数组"><a href="#5、不能构造泛型数组" class="headerlink" title="5、不能构造泛型数组"></a>5、不能构造泛型数组</h4><p>如：T[]</p>
<h4 id="6、泛型类的静态上下文中类型变量无效"><a href="#6、泛型类的静态上下文中类型变量无效" class="headerlink" title="6、泛型类的静态上下文中类型变量无效"></a>6、泛型类的静态上下文中类型变量无效</h4><p>如：private static T abc;//报错</p>
<h4 id="7、不能抛出或捕获泛型类的实例"><a href="#7、不能抛出或捕获泛型类的实例" class="headerlink" title="7、不能抛出或捕获泛型类的实例"></a>7、不能抛出或捕获泛型类的实例</h4><p>如：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;<span class="keyword">catch</span>(T e)&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>不过，在异常规范中使用类型变量是允许的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Throwable&gt; <span class="function"><span class="keyword">void</span> <span class="title">doWork</span><span class="params">(T t)</span> thows T</span>&#123;<span class="comment">//ok</span></span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;<span class="keyword">catch</span>(Throwable realCause)&#123;</span><br><span class="line">        t.initCause(realCause);</span><br><span class="line">        <span class="keyword">throw</span> t;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="8、注意泛型的继承"><a href="#8、注意泛型的继承" class="headerlink" title="8、注意泛型的继承"></a>8、注意泛型的继承</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"> A extends B</span><br><span class="line">Pair&lt;B&gt; 不是 Pair&lt;A&gt;  的子类，会类型擦除的</span><br></pre></td></tr></table></figure>
<h3 id="七、通配符类型"><a href="#七、通配符类型" class="headerlink" title="七、通配符类型"></a>七、通配符类型</h3><p>能一定程度解决上面泛型不能继承的问题<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Pair&lt;? extends B&gt;</span><br></pre></td></tr></table></figure></p>
<p>如果调用上面方法的set方法会报错，不能设置值，因为不能确定是什么类型的值，可以get</p>
<ul>
<li><p>? extends B 不能设置值，如果是集合（如List）就不能添加值。因为不能到是什么类型的值，但是能获取值，获取的值一定是B的子类，可以用B接收</p>
</li>
<li><p>？ super B 不能获取值，能设置/添加值，因为一定是B的子类，不能获取值，如果获取出来用什么接收呢？因为类型不确定。</p>
</li>
<li>？ 不能添加也不能获取，道理同上，但是能加入null，因为对象都能表示为null</li>
</ul>
<h3 id="八、反射和泛型"><a href="#八、反射和泛型" class="headerlink" title="八、反射和泛型"></a>八、反射和泛型</h3><blockquote>
<p>未完。。</p>
</blockquote>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>赏</span>
  </button>
  <div id="QR" style="display: none;">
  <div>我看他们都放打赏功能，我也放，只为了看起来逼格高</div>

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="卡卢比 WeChat Pay"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/zhifubao.jpg" alt="卡卢比 Alipay"/>
        <p>支付宝支付</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    卡卢比
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.lyq3.com/2017/11/07/JavaCore/java_genericity/" title="Java基础之泛型总结">http://blog.lyq3.com/2017/11/07/JavaCore/java_genericity/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JAVA/" rel="tag"><i class="fa fa-tag"></i> JAVA</a>
          
            <a href="/tags/泛型/" rel="tag"><i class="fa fa-tag"></i> 泛型</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/31/JavaCore/Java8_lambda/" rel="next" title="Java8新特性之Lambda表达式总结">
                <i class="fa fa-chevron-left"></i> Java8新特性之Lambda表达式总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/29/SpringCloud/SpringCloud-core/" rel="prev" title="微服务学习之微服务基础">
                微服务学习之微服务基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/touxiang.jpg"
               alt="卡卢比" />
          <p class="site-author-name" itemprop="name">卡卢比</p>
           
              <p class="site-description motion-element" itemprop="description">你不是努力<br/>只是看起来很努力而已</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">24</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/lyq3" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=hefk8ejk673F9PSr5uro" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、为什么使用泛型"><span class="nav-text">一、为什么使用泛型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、定义简单泛型类"><span class="nav-text">二、定义简单泛型类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义泛型类："><span class="nav-text">定义泛型类：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用泛型："><span class="nav-text">使用泛型：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、泛型方法"><span class="nav-text">三、泛型方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义泛型方法"><span class="nav-text">定义泛型方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用泛型方法"><span class="nav-text">使用泛型方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、类型变量的限定"><span class="nav-text">四、类型变量的限定</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五、类型擦除"><span class="nav-text">五、类型擦除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#六、约束与局限性"><span class="nav-text">六、约束与局限性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、不能用基本类型实例化类型参数"><span class="nav-text">1、不能用基本类型实例化类型参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、运行时类型查询只适用于原始类型"><span class="nav-text">2、运行时类型查询只适用于原始类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3、不能创建参数化类型的数组"><span class="nav-text">3、不能创建参数化类型的数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4、不能实例化类型变量"><span class="nav-text">4、不能实例化类型变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5、不能构造泛型数组"><span class="nav-text">5、不能构造泛型数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6、泛型类的静态上下文中类型变量无效"><span class="nav-text">6、泛型类的静态上下文中类型变量无效</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7、不能抛出或捕获泛型类的实例"><span class="nav-text">7、不能抛出或捕获泛型类的实例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#8、注意泛型的继承"><span class="nav-text">8、注意泛型的继承</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#七、通配符类型"><span class="nav-text">七、通配符类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#八、反射和泛型"><span class="nav-text">八、反射和泛型</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">卡卢比</span>

  
</div>


  <div class="powered-by">
    蜀ICP备17002589号
  </div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">
    聊原理滔滔不绝，写代码风生水起 &mdash;
  </div>
  <div class="theme-info">
    <p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>
  </div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytajjz9I';
      var conf = '5403fe58dfd9e28da540f4de17a6f45f';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  





  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2X0sx0lEavk9Gdr8PYUU0ic2-gzGzoHsz", "25Q9GXTLiNvfhIMMVltqH9J5");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
